package com.jhoncy.myproject.common.security.oauth.config;

import com.jhoncy.myproject.system.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * 自定义认证
 * @author zhuangqi
 * @@date 2017/3/3.
 */
@Component
public class MyAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private SysUserService sysUserService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String userName = authentication.getName();
        String passWord = (String) authentication.getCredentials();
        UserDetails user = sysUserService.loadUserByUsername(userName);
        if(user == null){
            throw new BadCredentialsException("Username not found.");
        }
        if (!passWord.equals(user.getPassword())){ ////TODO密码未加密
            throw new BadCredentialsException("Wrong password.");
        }

        Collection<? extends GrantedAuthority> authorities = user.getAuthorities();
        return new UsernamePasswordAuthenticationToken(user, passWord, authorities);
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
